package com.human.server.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.human.server.entity.Users;
import com.human.server.model.MessageType;
import com.human.server.model.R;
import com.human.server.model.UserResponse;
import com.human.server.service.UsersService;
import com.human.server.mapper.UsersMapper;
import org.springframework.stereotype.Service;

/**
* @author Admin
* @description 针对表【users(用户表)】的数据库操作Service实现
* @createDate 2025-09-16 23:44:28
*/
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users>
    implements UsersService{
    /**
     * 登录，判断账户密码是否错误
     */
    public R loginValid(Users user) {
        // 根据登录名查询用户
        Users localUser = this.baseMapper.selectOne(new LambdaQueryWrapper<Users>().eq(Users::getUsername, user.getUsername()));
        if (localUser == null) {
            return R.fail(MessageType.ACCOUNT_PASSWORD_ERROR);
        }

        // 校验密码
        if (!localUser.getPassword().equals(user.getPassword())) {
            return R.fail(MessageType.ACCOUNT_PASSWORD_ERROR);
        }

        // 校验通过，返回成功
        StpUtil.login(localUser.getId());
        UserResponse userResponse = new UserResponse();
        userResponse.setToken(StpUtil.getTokenValue());
        localUser.setPassword(null);
        userResponse.setUser(localUser);
        return R.success(userResponse);
    }

    public void resetPassword(Users user) {

        this.baseMapper.update(new LambdaUpdateWrapper<Users>().set(Users::getPassword, user.getPassword())
                .eq(Users::getId, user.getId()));
    }
}




